package com.archstoday.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.widget.TextView;

import com.archstoday.R;
import com.archstoday.common.AsRes;
import com.archstoday.common.SpfUtils;
import com.archstoday.entity.BaseEntity;
import com.archstoday.entity.UserInfoEntity;
import com.archstoday.utils.OAuthUtils;
import com.archstoday.utils.ProcessUtils;
import com.archstoday.utils.ToolUtils;
import com.base.http.common.BaseHttpClient;
import com.base.utils.CropUtil;
import com.base.utils.ImageUtil;
import com.base.utils.MySharedPreferencesMgr;
import com.base.utils.StringUtil;
import com.gifdialog.DialogUtil;
import com.gifdialog.GifDialog;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import de.hdodenhof.circleimageview.CircleImageView;

/**
 * 用户信息编辑
 */
public class EditUserActivity extends AsScrollBaseActivity {

    private TextView mTitleTv;
    private CircleImageView mHeadIcon;
    private TextView mSexTv;
    private TextView mUserNickNameTv;
    private TextView mUserAddressTv;
    private TextView mUserAgeTv;
    private String[] sexs = new String[]{"男", "女"};
    private String sex;

    private GifDialog loadingDialog;

    @Override
    protected void initView(Bundle bundle) {
        setContentView(R.layout.activity_edit_user);
        mTitleTv = (TextView) findViewById(R.id.title_tv);
        mHeadIcon = (CircleImageView) findViewById(R.id.edit_user_head_icon);
        mSexTv = (TextView) findViewById(R.id.edit_user_sex_tv);
        mUserNickNameTv = (TextView) findViewById(R.id.edit_user_nick_btn_value);
        mUserAddressTv = (TextView) findViewById(R.id.edit_user_address_btn_value);
        mUserAgeTv = (TextView) findViewById(R.id.edit_user_age_btn_value);
    }

    @Override
    protected void initData(Bundle bundle) {
        mHeadIcon.setImageResource(R.mipmap.user_header_icon);
        mTitleTv.setText(R.string.edit_user_title);

        UserInfoEntity.DataBean dataBean = OAuthUtils.getInstance().getUserInfo();
        if (dataBean != null && dataBean.getUserImg() != null) {
            ImageUtil.setCropBitmap(mContext, mHeadIcon,
                    dataBean.getUserImg(), R.mipmap.user_header_icon);
        } else {
            mHeadIcon.setImageResource(R.mipmap.user_header_icon);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        UserInfoEntity.DataBean dataBean = OAuthUtils.getInstance().getUserInfo();
        if (dataBean == null) {
            return;
        }

        mSexTv.setText(StringUtil.equest(
                OAuthUtils.getInstance().getUserInfo().getSex(), "female")
                ? "女" : "男");

        mUserNickNameTv.setText(ProcessUtils.procesText(dataBean.getName()));

        String address = ProcessUtils.procesText(dataBean.getProvince()) + " "
                + ProcessUtils.procesText(dataBean.getCity()) + " "
                + ProcessUtils.procesText(dataBean.getDistrict());
        if (!TextUtils.isEmpty(address)) {
            mUserAddressTv.setText(address);
        }

        mUserAgeTv.setText(String.valueOf(dataBean.getAge()));
    }

    @Override
    protected void initListener() {
        setOnClickListener(R.id.back_btn);
        setOnClickListener(R.id.edit_user_head_btn);
        setOnClickListener(R.id.edit_user_address_btn_rl);
        setOnClickListener(R.id.edit_user_age_btn_rl);
        setOnClickListener(R.id.edit_user_sex_btn);
        setOnClickListener(R.id.edit_user_nick_btn_rl);
    }

    @Override
    public void treatClickEvent(int id) {
        Intent intent;
        switch (id) {
            case R.id.back_btn:
                appFinish();
                break;
            case R.id.edit_user_head_btn:
                showImgTypeDialog();
                break;
            case R.id.edit_user_nick_btn_rl:
                intent = new Intent(mContext, EditInfoActivity.class);
                intent.putExtra("isNick", true);
                startActivity(intent);
                break;
            case R.id.edit_user_address_btn_rl:
                intent = new Intent(mContext, ChoiceAddressActivity.class);

                String address = mUserAddressTv.getText().toString().trim();
                String[] data = address.split(" ");
                if (data != null) {
                    if (data.length > 0) {
                        intent.putExtra("p", data[0]);
                    }
                    if (data.length > 1) {
                        intent.putExtra("c", data[1]);
                    }
                    if (data.length > 2) {
                        intent.putExtra("d", data[2]);
                    }
                }
                startActivityForResult(intent, 50);
                break;
            case R.id.edit_user_age_btn_rl:
                intent = new Intent(mContext, EditInfoActivity.class);
                intent.putExtra("isNick", false);
                startActivity(intent);
                break;
            case R.id.edit_user_sex_btn:
                sex = mSexTv.getText().toString();
                int index;
                if (sex.equals(sexs[0])) {
                    index = 0;
                } else {
                    index = 1;
                }
                AlertDialog dialog = new AlertDialog.Builder(this)
                        .setTitle("性别")
                        .setSingleChoiceItems(sexs, index, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                sex = sexs[which];
                            }
                        })
                        .setPositiveButton(R.string.submit_btn, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                modifyInfo(sex.equals(sexs[0]) ? "male" : "female");
                            }
                        })
                        .setNegativeButton(R.string.cancel_btn, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        })
                        .create();
                dialog.show();
                break;
        }
    }

    private void uploadHead(String img) {
        loadingDialog = new DialogUtil().showGifdialog(mContext);
        loadingDialog.show();

        try {
            initParameter();
            mParams.put("userId", MySharedPreferencesMgr.getString(SpfUtils.USER_ID, ""));
            mParams.put("token", MySharedPreferencesMgr.getString(SpfUtils.USER_TOKEN, ""));
            mParams.put("userImg", URLEncoder.
                    encode("data:image/jpeg;base64," + img, "UTF-8"));

            sendEncryptPostRequest(AsRes.getInstance().getUrl(AsRes.UPLOAD_USER_HEAD),
                    AsRes.UPLOAD_USER_HEAD, mParams, BaseEntity.class);
        } catch (UnsupportedEncodingException e) {

        }
    }

    private void modifyInfo(String sex) {
        loadingDialog = new DialogUtil().showGifdialog(mContext);
        loadingDialog.show();

        initParameter();
        mParams.put("userId", MySharedPreferencesMgr.getString(SpfUtils.USER_ID, ""));
        mParams.put("token", MySharedPreferencesMgr.getString(SpfUtils.USER_TOKEN, ""));
        mParams.put("sex", sex);

        sendEncryptPostRequest(AsRes.getInstance().getUrl(AsRes.MODIFY_USER_INFO),
                AsRes.MODIFY_USER_INFO, mParams, BaseEntity.class);
    }

    @Override
    protected void onSuccess(String content, BaseHttpClient client, Object parse) {
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }
        if (client.getUrlIdentifier() == AsRes.MODIFY_USER_INFO) {
            BaseEntity entity = (BaseEntity) parse;
            if (ToolUtils.isSuccess(entity.getStatus())) {
                showToast("性别修改成功");

                UserInfoEntity.DataBean dataBean = OAuthUtils.getInstance().getUserInfo();
                if (dataBean != null) {
                    dataBean.setSex(sex.equals(sexs[0]) ? "male" : "female");
                    OAuthUtils.getInstance().setUserInfo(dataBean);
                }
                mSexTv.setText(sex);
            } else if (entity.getStatus() == 10005) {
                MySharedPreferencesMgr.setString(SpfUtils.USER_ID, "");
                MySharedPreferencesMgr.setString(SpfUtils.USER_TOKEN, "");
                OAuthUtils.getInstance().cleanUserInfo();

                showToast("登录信息已过期，请重新登录");
                Intent intent = new Intent(mContext, LoginActivity.class);
                startActivity(intent);
            } else {
                showToast(entity.getMsg());
            }
        } else if (client.getUrlIdentifier() == AsRes.UPLOAD_USER_HEAD) {
            BaseEntity entity = (BaseEntity) parse;
            if (ToolUtils.isSuccess(entity.getStatus())) {
                showToast("头像上传成功");
            } else if (entity.getStatus() == 10005) {
                MySharedPreferencesMgr.setString(SpfUtils.USER_ID, "");
                MySharedPreferencesMgr.setString(SpfUtils.USER_TOKEN, "");
                OAuthUtils.getInstance().cleanUserInfo();

                showToast("登录信息已过期，请重新登录");
                Intent intent = new Intent(mContext, LoginActivity.class);
                startActivity(intent);
            } else {
                showToast(entity.getMsg());
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case SELECT_GALLERY:
                if (resultCode == RESULT_OK) {
//                    cropPhoto(data.getData());
                    cropImageUri = Uri.fromFile(fileCropUri);
                    Uri newUri = Uri.parse(CropUtil.getPath(this, data.getData()));
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                        newUri = FileProvider.getUriForFile(this, "com.base.provider", new File(newUri.getPath()));
                    }
                    cropImageUri(newUri, cropImageUri);
                }
                break;
            case SELECT_CAMERA:
                if (resultCode == RESULT_OK) {
//                    File temp = new File(Environment.getExternalStorageDirectory() + "/head.jpg");
//                    cropPhoto(Uri.fromFile(temp));
                    cropImageUri = Uri.fromFile(fileCropUri);
                    cropImageUri(imageUri, cropImageUri);
                }
                break;
            case CROP_PHOTO:
//                if (data != null) {
//                    Bundle extras = data.getExtras();
//                    if (extras != null) {
//                        Bitmap head = extras.getParcelable("data");
//                        if (head != null) {
//                            mHeadIcon.setImageBitmap(head);
////                            File file = CropUtil.makeTempFile(mContext, head,
////                                    FileNameGenerator.generator(System.currentTimeMillis()
////                                            + "head_icon.png"));
////                            String file_path = file.getAbsolutePath();
//                            uploadHead(ToolUtils.bitmaptoString(
//                                    ToolUtils.compressImage(head)));
//                        }
//                    }
//                }
                try {
                    Bitmap head = MediaStore.Images.Media.getBitmap(mContext.getContentResolver(), cropImageUri);
                    if (head != null) {
                        mHeadIcon.setImageBitmap(head);
                        uploadHead(ToolUtils.bitmaptoString(
                                ToolUtils.compressImage(head)));
                    }
                } catch (IOException e) {

                }
                break;
            case 50:
                if (resultCode == 50) {
                    appFinish();
                }
                break;
        }
    }
}